<?php

namespace app\admin\model\handler;

use think\Model;
use traits\model\SoftDelete;
use app\admin\library\Auth;

class Handler extends Model
{

    use SoftDelete;


    // 表名
    protected $name = 'handler';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text'
    ];

    protected static function init()
    {
        self::beforeUpdate(function ($row) {
            $changedata = $row->getChangedData();
            $origin = $row->getOriginData();
            if (isset($changedata['money']) && (function_exists('bccomp') ? bccomp($changedata['money'], $origin['money'], 2) !== 0 : (double)$changedata['money'] !== (double)$origin['money'])) {


                // 获取管理员信息和IP地址
                $adminId = session('admin.id') ?: 0;
                $adminName = session('admin.nickname') ?: '系统';
                $ip = request()->ip();

                $changeAmount = $changedata['money'] - $origin['money'];
                HandlerMoneyLog::create(['handler_id' => $row['id'], 'money' => $changeAmount, 'before' => $origin['money'], 'after' => $changedata['money'], 'memo' => sprintf(
                    '管理员操作：%s(%s) %s了金额 %s，从 %s 变更为 %s | IP：%s',
                    $adminName,
                    $adminId,
                    $changeAmount > 0 ? '增加' : '减少',
                    abs($changeAmount),
                    $origin['money'],
                    $changedata['money'],
                    $ip
                )]);
            }
        });
    }

    public function getOriginData()
    {
        return $this->origin;
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 3')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }


    public function level()
    {
        return $this->belongsTo('Level', 'level_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
